﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using KVB.Common;
using Customer_Profile.eCard.DBDao;
using Customer_Profile.Admin;
using System.IO;

namespace Customer_Profile.eCard.Settle
{
    public partial class settle_application : System.Web.UI.Page
    {
        int deal_no;
        //string strCpartyID;
        const string UploadDirectory = "~/eCard/tempUpload/";
        const int ThumbnailSize = 100;

        string strUserName = "";
        string strUserID = "";
        string strEntity = "";

        string settle_id = "";
        protected void Page_Load(object sender, EventArgs e)
        {   
            Comm.CheckSession(this.Page, "/login.aspx", "usermodel");
            if (Session["usermodel"] != null)
            {
                strUserID = ((UserInfoEntity)Session["usermodel"]).UserLoginId;
                strUserName = ((UserInfoEntity)Session["usermodel"]).UserName;
                strEntity = ((UserInfoEntity)Session["usermodel"]).UserOffice;
            }
            else
            {
                Log.WriteDefaultLog("main_01 Page_Load", "Session is null");
                return;
            }


            if (Request["deal_no"] != null)
            {
                deal_no = int.Parse(Request["deal_no"].ToString());
                hidDeal_no.Value = Request["deal_no"].ToString();
            }

            this.txtPayAmount.Attributes.Add("readonly", "readonly");                       

            if (Request["settle_id"] != null)
            {
                settle_id = Request["settle_id"].ToString();
            }

            if (!Page.IsPostBack)
            {
                DataSet dsAgent = SaleAgentDao.getSettleAgentList("Y");
                DropSettleAgent.DataSource = dsAgent;
                DropSettleAgent.DataTextField = "settle_agent_name";
                DropSettleAgent.DataValueField = "settle_agent_id";
                DropSettleAgent.DataBind();

                //结算添加情况
                if (Request["deal_no"] != null)
                {
                    //如果是三国系列就可以修改。算了，还是做一个配置文件吧。哪些产品结算可以修改手续费。
                    if (!Comm.ifcanUpdateSettleFee(deal_no.ToString()))
                    {
                        this.txtSettleFee.Attributes.Add("readonly", "readonly");
                    }
                    bindSettleAmount(deal_no);
                    bindSettleAccount(int.Parse(hidCpartyID.Value.ToString()));
                    bindAttachList(deal_no);
                    btnSubmit.Enabled = false;
                    btnCancel.Enabled = false;
                }

                //结算修改情况
                if (Request["settle_id"] != null)
                {
                    hidSettle_id.Value = Request["settle_id"].ToString();
                    //检查交易是否被锁定，如果没锁定，报错，请联系管理员。
                    if (!checkIfLocked(hidSettle_id.Value.Trim()))
                    {
                        //1,锁定，
                        DealDao.LockRefDeals(hidSettle_id.Value.Trim());
                        //2,发一条错误短信给系统管理员。
                        Log.WriteDefaultLog(strUserID + " " + strEntity + " 未锁定交易，重复提交错误记录：", hidSettle_id.Value);
                        Comm.SendSMS(strUserID + " " + strEntity + " 未锁定交易，重复提交错误记录：" + hidSettle_id.Value);
                    }

                    //绑定交易信息，hidid还款账户绑定，并且为hidid赋值，hidCpartyID客户的cpartyID信息。
                    bindOldDealInfo(Request["settle_id"].ToString().Trim());
                    //绑定客户回款账户信息，并选中该条信息。
                    bindSettleAccount(int.Parse(hidCpartyID.Value.ToString().Trim()));
                    //绑定附件。
                    bindAttachList(deal_no);
                }
            }
        }

        //检查交易是否被锁定，如果没有被锁定，是有问题的。
        private bool checkIfLocked(string ref_settle_id)
        {
            bool if_locked =false;

            DataSet ds = DealDao.getIfLocked(ref_settle_id);
            if (!Comm.DataSetIsEmpty(ds))
            {
                string if_slocked = ds.Tables[0].Rows[0][0].ToString();
                if (if_slocked.ToUpper().Trim().Equals("Y"))
                    if_locked = true;
                else
                    if_locked = false;
            }
            else
            {
                Log.WriteDefaultLog("checkIfLocked:" + ref_settle_id + "\r\n", "ds不能为空，如果为空那里出错了");
            }
            
            return if_locked;
        }

        //检查交易是否被锁定,根据dealno
        private bool checkIfLocked_bydealno(string ref_deal_no)
        {
            bool if_locked = false;

            DataSet ds = DealDao.getIfLocked_bydealno(ref_deal_no);
            if (!Comm.DataSetIsEmpty(ds))
            {
                string if_slocked = ds.Tables[0].Rows[0][0].ToString();
                if (if_slocked.ToUpper().Trim().Equals("Y"))
                    if_locked = true;
                else
                    if_locked = false;
            }
            else
            {
                Log.WriteDefaultLog("checkIfLocked_bydealno:" + deal_no + "\r\n", "ds不能为空，如果为空那里出错了");
            }

            return if_locked;
        }


        private void bindOldDealInfo(string ref_settel_id)
        {
            try
            {
                DataSet ds = DealDao.getSettleInfobySettleID(ref_settel_id);
                //hidid还款账户绑定，并且为hidid赋值，hidCpartyID客户的cpartyID信息。
                deal_no = int.Parse(ds.Tables[0].Rows[0]["deal_no"].ToString());
                //如果是三国系列就可以修改。算了，还是做一个配置文件吧。哪些产品结算可以修改手续费。
                if (!Comm.ifcanUpdateSettleFee(deal_no.ToString()))
                {
                    this.txtSettleFee.Attributes.Add("readonly", "readonly");
                }

                lblCpartyName.Text = ds.Tables[0].Rows[0]["cparty_name"].ToString();
                if (ds.Tables[0].Rows[0]["if_isExtension"].ToString().Equals("Y"))
                {
                    lblCommsionWarning.Text = "此交易为续购，手续费收取请参照总部下发规章执行。";
                    string strTemp = ds.Tables[0].Rows[0]["extend_id"].ToString();
                    lblCommsionWarning.Text += "<a href='/eCard/Match/ExtendOriginalDeal.aspx?extend_id=" + strTemp + "' target='_blank'>查看原单</a>";
                }
                else
                {
                    lblCommsionWarning.Text = "";
                }

                hidDeal_no.Value = ds.Tables[0].Rows[0]["deal_no"].ToString();
                hidCpartyID.Value = ds.Tables[0].Rows[0]["cparty_id"].ToString();                
                txtcardno.Text = ds.Tables[0].Rows[0]["card_no"].ToString();
                txtCommssion.Text = ds.Tables[0].Rows[0]["settle_commission_percent"].ToString();
                txtPayAmount.Text = ds.Tables[0].Rows[0]["pay_amount"].ToString();
                hidPayAmount.Value = ds.Tables[0].Rows[0]["pay_amount"].ToString();
                txtRemark.Text = ds.Tables[0].Rows[0]["remark"].ToString();
                txtSettleAmount.Text = ds.Tables[0].Rows[0]["settle_amount"].ToString();
                txtSettleFee.Text = ds.Tables[0].Rows[0]["settle_fee"].ToString();
                DropSettleAgent.Items.FindByValue(ds.Tables[0].Rows[0]["settle_agent_id"].ToString()).Selected = true;

                accountname.Text=ds.Tables[0].Rows[0]["account_name"].ToString();
                accountno.Text=ds.Tables[0].Rows[0]["account_no"].ToString();
                bankname.Text=ds.Tables[0].Rows[0]["bank_name"].ToString();
                branch.Text=ds.Tables[0].Rows[0]["bank_branch"].ToString();
                subbranch.Text=ds.Tables[0].Rows[0]["bank_sub_branch"].ToString();
                location.Text=ds.Tables[0].Rows[0]["location"].ToString();
                city.Text = ds.Tables[0].Rows[0]["city"].ToString();
                lblBackReason.Text = ds.Tables[0].Rows[0]["back_reason"].ToString();
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("settle_application.bindOldDealInfo", ex.ToString());
                Response.Write(ex.ToString());
            }
        }

        private void bindSettleAccount(int cparty_id)
        {
            try
            {
                DataSet ds = SaleAgentDao.getSettleCommonBankAccount(cparty_id);
                if (ds != null && ds.Tables.Count > 0)
                {
                    DropBackAccount.DataSource = ds.Tables[0];
                    DropBackAccount.DataTextField = "account_no";
                    DropBackAccount.DataValueField = "Bankaccount_id";
                    DropBackAccount.DataBind();
                    ListItem liAll = new ListItem();
                    liAll.Text = "请选择";
                    liAll.Value = "";
                    DropBackAccount.Items.Insert(0, liAll);
                }
               
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("bindGrid", ex.ToString());
            }
        }

        private void bindSettleAmount(int deal_no)
        {
            try
            {
                DataSet ds = SaleAgentDao.getDealBalance(deal_no);
                hidCpartyID.Value = ds.Tables[0].Rows[0]["cparty_id"].ToString();
                lblCpartyName.Text = ds.Tables[0].Rows[0]["cparty_name"].ToString();
                if (ds.Tables[0].Rows[0]["if_isExtension"].ToString().Equals("Y"))
                {
                    lblCommsionWarning.Text = "此交易为续购，手续费收取请参照总部下发规章执行。";
                    string strTemp = ds.Tables[0].Rows[0]["extend_id"].ToString();
                    lblCommsionWarning.Text += "<a href='/eCard/Match/ExtendOriginalDeal.aspx?extend_id=" + strTemp + "' target='_blank'>查看原单</a>";
                }
                else
                {
                    lblCommsionWarning.Text = "";
                }

                txtcardno.Text = ds.Tables[0].Rows[0]["card_no"].ToString();
                txtSettleAmount.Text = ds.Tables[0].Rows[0]["deal_balance"].ToString();
                txtCommssion.Text = ds.Tables[0].Rows[0]["settle_percent"].ToString();
                txtSettleFee.Text = ds.Tables[0].Rows[0]["settle_fee"].ToString();
                txtPayAmount.Text = ds.Tables[0].Rows[0]["pay_amount"].ToString();
                hidPayAmount.Value = ds.Tables[0].Rows[0]["pay_amount"].ToString();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                CpartyDao.addCpartyBank(hidCpartyID.Value, accountname.Text, accountno.Text, bankname.Text, branch.Text, subbranch.Text, location.Text, city.Text);
                bindSettleAccount(int.Parse(hidCpartyID.Value));
                KVB.Common.JavaScript.ViewAlertMsg("已经成功添加到常用账户，下次可以直接选用。");
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("bindGrid", ex.ToString());
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string view_name = "";
            string attach_name = "";
            string attach_type = "";
            string attach_size = "";
            string attach_url = "";

            FileInfo fileInfo = new FileInfo(FileUpload1.FileName);
            attach_name = DateTime.Now.ToString("yyyyMMddHHmmssfff") + fileInfo.Name;
            string savePathName = MapPath(UploadDirectory) + attach_name;
            FileUpload1.SaveAs(savePathName);

            view_name = fileInfo.Name;
            attach_type = FileUpload1.PostedFile.ContentType.ToString();
            attach_size = FileUpload1.PostedFile.ContentLength / 1024 + "K";
            attach_url = "/eCard/tempUpload/" + attach_name;
            AttachDao.AddAttach(int.Parse(hidDeal_no.Value.Trim()), view_name, attach_name, attach_type, attach_size, attach_url, "SA");
            bindAttachList(int.Parse(hidDeal_no.Value.Trim()));
        }

        private void bindAttachList(int deal_no)
        {
            try
            {
                int iDeal_no = deal_no;
                DataSet dsAttachList = AttachDao.getAttachList(iDeal_no, "SA");
                gridAttach.DataSource = dsAttachList;
                gridAttach.DataBind();
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("settle_application.bindAttachList", ex.ToString());
                Response.Write(ex.ToString());
            }
        }

        protected void btnSave_Click1(object sender, EventArgs e)
        {
            try
            {
                //1,向settle_subinfo里面保存数据
                //2,修改mmdeals的状态
                //3,锁定该笔记录
                decimal dSettle_amount = decimal.Parse(txtSettleAmount.Text);
                decimal dSettle_fee = decimal.Parse(txtSettleFee.Text);
                decimal dCommission = decimal.Parse(txtCommssion.Text);
                decimal dPay_amount = decimal.Parse(hidPayAmount.Value.Trim());
                string settle_agent_id = DropSettleAgent.SelectedItem.Value;

                string account_name = accountname.Text.Trim();
                string account_no = accountno.Text.Trim();
                string bank_name = bankname.Text.Trim();
                string bank_branch = branch.Text.Trim();
                string bank_sub_branch = subbranch.Text.Trim();
                string bankaccount_location = location.Text.Trim();
                string bankaccount_city = city.Text.Trim();

                string remark = txtRemark.Text;
                string status = "";
                string message = "";

                //int settle_bankAccount = int.Parse(hidid.Value.ToString());

                if (hidSettle_id.Value.Equals(""))
                {
                    //检查deal是不是锁定状态，如果是锁定了则不允许再次保存了。
                    if (checkIfLocked_bydealno(deal_no.ToString()))
                    {
                        lblWarning.Text = "交易被锁定，不能添加结算申请。";
                    }
                    else
                    {
                        DealDao.DealssettleInsert(deal_no, dSettle_amount, dCommission, dSettle_fee, dPay_amount, settle_agent_id,
                            account_name, account_no, bank_name, bank_branch, bank_sub_branch, bankaccount_location, bankaccount_city,
                            strUserID, remark, out status, out message);
                        if (status.Equals("Y"))
                        {
                            hidSettle_id.Value = message;
                            //Response.Redirect("settle_application.aspx?settle_id=" + hidSettle_id.Value.Trim(), false);
                            KVB.Common.JavaScript.ViewMsgGoUrl("settle_application.aspx?settle_id=" + hidSettle_id.Value.Trim(), "保存成功！");
                            #region
                            //lblWarning.Text = "新增保存成功！";
                            //
                            //bindOldDealInfo(hidSettle_id.Value.Trim());
                            ////如果保存成功了，则提交到总部为可用。
                            //btnSubmit.Enabled = true;
                            //btnCancel.Enabled = true;
                            #endregion
                        }
                        else
                        {
                            lblWarning.Text = message;
                        }
                    }
                }
                else
                {
                    DealDao.DealssettleUpdate(int.Parse(hidSettle_id.Value), dSettle_amount, dCommission, dSettle_fee, dPay_amount, settle_agent_id,
                        account_name, account_no, bank_name, bank_branch, bank_sub_branch, bankaccount_location, bankaccount_city,
                        remark, out status, out message);
                    if (status.Equals("Y"))
                    {
                        bindOldDealInfo(hidSettle_id.Value.Trim());
                        lblWarning.Text = "修改保存成功！";
                    }
                    else
                    {
                        lblWarning.Text = message;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("结算申请录入：", ex.ToString());
                Response.Write("系统出错了，请联系系统管理员。<br>"+ex.ToString());
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            //1,取消锁定
            //2,删除settle_subinfo里面的数据
            //3,修改mmdeals为原始状态。
            string status = "";
            string message = "";
            DealDao.DealssettleCancel(int.Parse(hidSettle_id.Value), out status, out message);
            if (status.Equals("Y"))
            {
                lblWarning.Text = message;
                //取消了，转换页面
                Response.Redirect("needSettle_search.aspx", false);
            }
            else
            {
                lblWarning.Text = message;
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                string status = "";
                string message = "";

                //检查交易是否被锁定，如果没锁定，报错，请联系管理员，发短信给管理员
                if (!checkIfLocked(hidSettle_id.Value.Trim()))
                {
                    //1,锁定，
                    DealDao.LockRefDeals(hidSettle_id.Value.Trim());
                    //2,发一条错误短信给系统管理员。
                    Log.WriteDefaultLog(strUserID + " " + strEntity + " 未锁定交易，重复提交错误记录：", hidSettle_id.Value);
                    Comm.SendSMS(strUserID + " " + strEntity + " 提交结算信息到总部发现未锁定交易，重复提交错误记录：" + hidSettle_id.Value);
                }

                //检查一下是否有多笔在申请中的情况。
                if (DealDao.check_ifRepeat_requestSettle(settle_id))
                {
                    KVB.Common.Log.WriteDefaultLog("结算复核审核：", settle_id + "存在多笔未结束的结算申请。");
                    //strScript = "<script>alert('审核失败！settle id :" + settle_id + ":改笔原始交易存在多笔未结束的结算申请！请联系管理员');</script>";
                    lblWarning.Text = "审核失败！settle id :" + settle_id + ":改笔原始交易存在多笔未结束的结算申请！请联系管理员;";
                }
                else
                {
                    DealDao.DealssettleSubmit(int.Parse(hidSettle_id.Value), out status, out message);
                    if (status.Equals("Y"))
                    {
                        lblWarning.Text = message;
                        //提交了，转回页面
                        KVB.Common.JavaScript.ViewMsgGoUrl("needSettle_search.aspx", "数据已经提交成功，请等待总部审核！");
                    }
                    else
                    {
                        lblWarning.Text = message;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("结算申请提交到交易总部出错了：", ex.ToString());
                Response.Write("系统出错了，请联系系统管理员!<br>"+ex.ToString());
            }
        }

        protected void gridAttach_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            try
            {
                if (e.ButtonID != "Delete") return;
                int attach_id = int.Parse(gridAttach.GetRowValues(e.VisibleIndex, "attach_id").ToString());
                int temp_deal_no = int.Parse(gridAttach.GetRowValues(e.VisibleIndex, "deal_no").ToString());
                AttachDao.DeleteAttach(attach_id);
                bindAttachList(temp_deal_no);
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
                Log.WriteDefaultLog("settle_application.gridAttach_CustomButtonCallback", ex.ToString());
            }
        }

        protected void DropBackAccount_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = SaleAgentDao.getSettleCommonBankAccountInfo(int.Parse(DropBackAccount.SelectedItem.Value.ToString()));
                if (ds != null && ds.Tables.Count > 0)
                {
                    accountname.Text = ds.Tables[0].Rows[0]["account_name"].ToString();
                    accountno.Text = ds.Tables[0].Rows[0]["account_no"].ToString();
                    bankname.Text = ds.Tables[0].Rows[0]["bank_name"].ToString();
                    branch.Text = ds.Tables[0].Rows[0]["bank_branch"].ToString();
                    subbranch.Text = ds.Tables[0].Rows[0]["bank_sub_branch"].ToString();
                    location.Text = ds.Tables[0].Rows[0]["location"].ToString();
                    city.Text = ds.Tables[0].Rows[0]["city"].ToString();
                }
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("DropBackAccount_SelectedIndexChanged ", ex.ToString());
                Response.Write(ex.ToString());
            }
        }
    }
}